package com.dai.spec.gxk.controller;

import com.dai.spec.common.annotation.Log;
import com.dai.spec.common.core.controller.BaseController;
import com.dai.spec.common.core.domain.AjaxResult;
import com.dai.spec.common.core.page.TableDataInfo;
import com.dai.spec.common.enums.*;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.StringUtils;
import com.dai.spec.common.utils.poi.ExcelUtil;
import com.dai.spec.gxk.domain.CourseApplication;
import com.dai.spec.gxk.service.CourseApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程申请管理Controller
 *
 * @author daikl
 * @date 2024-02-29
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/gxk/courseApplication")
@Api("课程申请管理")
public class CourseApplicationController extends BaseController {

    private final CourseApplicationService courseApplicationService;

    public CourseApplicationController(CourseApplicationService courseApplicationService) {
        this.courseApplicationService = courseApplicationService;
    }

    /**
     * 课程申请
     */
    @ApiOperation("课程申请")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:applicate')")
    @Log(title = "课程信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseApplication courseApplication) {
        this.validateCourse(courseApplication);

        return toAjax(courseApplicationService.saveApplication(courseApplication));
    }

    /**
     * 获取课程信息管理详细信息
     */
    @ApiOperation("获取课程详细信息")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(courseApplicationService.getById(id));
    }

    /**
     * 修改课程申请
     */
    @ApiOperation("修改课程申请")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:edit')")
    @Log(title = "修改课程申请", businessType = BusinessType.UPDATE)
    @PutMapping("/myApplication/edit")
    public AjaxResult edit(@RequestBody CourseApplication courseApplication) {
        this.validateCourse(courseApplication);

        if (!ApprovalStatus.PENDING_APPROVAL.getCode().equals(courseApplication.getApprovalStatus())) {
            throw new BaseException("审批状态不为待审批，不能进行修改！");
        }
        return toAjax(courseApplicationService.updateById(courseApplication));
    }

    /**
     * 删除课程申请
     */
    @ApiOperation("删除课程申请")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:remove')")
    @Log(title = "删除课程申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(courseApplicationService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 导出课程申请
     */
    @ApiOperation("导出课程申请列表")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:export')")
    @Log(title = "导出课程申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseApplication courseApplication) {
        List<CourseApplication> applicationList = courseApplicationService.queryMyApplicationList(courseApplication);
        List<CourseApplication> courseList = applicationList.stream().map(item -> {
            CourseApplication coveredCourse = this.coverCourse(item);
            return coveredCourse;
        }).collect(Collectors.toList());
        ExcelUtil<CourseApplication> util = new ExcelUtil<CourseApplication>(CourseApplication.class);
        util.exportExcel(response, courseList, "课程申请信息数据");
    }

    private static CourseApplication coverCourse(CourseApplication item) {
        String department = item.getDepartment();
        item.setDepartment(DepartmentType.getValueByCode(department));

        String courseCycle = item.getCourseCycle();
        item.setCourseCycle(CourseCycleType.getValueByCode(courseCycle));

        String type = item.getType();
        item.setType(CourseType.getValueByCode(type));

        String status = item.getStatus();
        item.setStatus(CourseStatus.getValueByCode(status));

        String deliveryType = item.getDeliveryType();
        item.setDeliveryType(DeliveryType.getValueByCode(deliveryType));
        return item;
    }

    /**
     * 查询我的课程申请列表
     */
    @ApiOperation("查询我的课程申请列表")
    @PreAuthorize("@ss.hasPermi('gxk:myCourseApplication:list')")
    @GetMapping("/myApplication/list")
    public TableDataInfo listMyApplication(CourseApplication courseApplication) {

        if (courseApplication == null) {
            return null;
        }
        startPage();
        List<CourseApplication> courseApplicationList = courseApplicationService.queryMyApplicationList(courseApplication);
        if (courseApplicationList == null || courseApplicationList.isEmpty()) {
            // 没有数据时，返回一个空的分页对象
            return new TableDataInfo(Collections.emptyList(), 0);
        }

        return getDataTable(courseApplicationList);
    }

    /**
     * 查询课程申请待审批列表
     */
    @ApiOperation("查询待审批课程列表")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseApplication courseApplication) {
        startPage();
        List<CourseApplication> courseApplicationList = courseApplicationService.queryList(courseApplication);
        return getDataTable(courseApplicationList);
    }

    /**
     * 导出待审批课程
     */
    @ApiOperation("导出待审批课程列表")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplicationApproval:export')")
    @Log(title = "导出待审批课程列表", businessType = BusinessType.EXPORT)
    @PostMapping("/approval/export")
    public void exportApproval(HttpServletResponse response, CourseApplication courseApplication) {
        List<CourseApplication> applicationList = courseApplicationService.queryList(courseApplication);
        List<CourseApplication> courseList = applicationList.stream().map(item -> {
            CourseApplication coveredCourse = this.coverCourse(item);
            return coveredCourse;
        }).collect(Collectors.toList());
        ExcelUtil<CourseApplication> util = new ExcelUtil<CourseApplication>(CourseApplication.class);
        util.exportExcel(response, courseList, "待审批课程信息数据");
    }

    /**
     * 课程审批
     */
    @ApiOperation("课程审批")
    @PreAuthorize("@ss.hasPermi('gxk:courseApplication:approval')")
    @Log(title = "课程审批管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult approval(@RequestBody CourseApplication courseApplication) {
        this.validateCourse(courseApplication);

        return toAjax(courseApplicationService.approvalApplication(courseApplication));
    }

    /**
     * 课程字段校验
     *
     * @param course
     */
    private static void validateCourse(CourseApplication courseApplication) {
        if (null == courseApplication.getCredits()) {
            throw new BaseException("课程学分不能为空！");
        }
        if (StringUtils.isEmpty(courseApplication.getDepartment())) {
            throw new BaseException("开课院系不能为空!");
        }
        if (StringUtils.isEmpty(courseApplication.getCourseCycle())) {
            throw new BaseException("课程周期不能为空!");
        }
        if (null == courseApplication.getStartTime()) {
            throw new BaseException("课程开课时间不能为空!");
        }
//        if (StringUtils.isEmpty(courseApplication.getLocation())) {
//            throw new BaseException("上课地点不能为空!");
//        }
        if (null == courseApplication.getPlantCounts()) {
            throw new BaseException("课程容量不能为空!");
        }
        if (courseApplication.getPlantCounts() < 0) {
            throw new BaseException("课程容量必须大于0");
        }
        if (StringUtils.isEmpty(courseApplication.getType())) {
            throw new BaseException("课程类型不能为空!");
        }
        if (StringUtils.isEmpty(courseApplication.getDeliveryType())) {
            throw new BaseException("开课类型不能为空!");
        }
    }
}
